const weightStore = {
	namespaced: true,

	state: () => ({
		deviceName: '电子秤',
		status: 'disconnected',
		weight: 0,
		WeightStr: 0,
		batteryLevel: -1
	}),

	getters: {
		isConnected: state => state.status === 'connected',
		isConnecting: state => state.status === 'connecting',
		hasBatteryInfo: state => state.batteryLevel >= 0 && state.batteryLevel <= 100,
		formattedWeight: state => state.weight.toLocaleString()
	},

	mutations: {
		SET_DEVICE_NAME(state, deviceName) {
			state.deviceName = deviceName;
		},

		SET_STATUS(state, status) {
			state.status = status;
		},

		SET_WEIGHT(state, weight) {
			state.weight = Math.max(0, weight); // 确保重量不为负数
		},

		SET_WEIGHT_STR(state, WeightStr) {
			state.WeightStr = WeightStr; // 确保重量不为负数
		},
		SET_BATTERY_LEVEL(state, batteryLevel) {
			// 确保电池电量在有效范围内
			state.batteryLevel = Math.max(-1, Math.min(100, batteryLevel));
		},

		UPDATE_DEVICE_STATE(state, deviceState) {
			Object.keys(deviceState).forEach(key => {
				if (state.hasOwnProperty(key) && deviceState[key] !== undefined) {
					state[key] = deviceState[key];
				}
			});
		}
	},

	actions: {
		// 置零操作
		zeroReset({
			commit
		}) {
			console.log('📦 发送置零指令');
			commit('SET_WEIGHT', 0);
		},

		// 去皮操作
		tare({
			commit
		}) {
			console.log('📦 发送去皮指令');
			// 实际去皮逻辑在蓝牙回调中处理
		},

		// 更新设备连接状态
		updateStatus({
			commit
		}, status) {
			if (['disconnected', 'connecting', 'connected', 'error'].includes(status)) {
				commit('SET_STATUS', status);
			} else {
				console.warn('⚠️ 无效的状态值:', status);
			}
		},

// 更新重量
updateWeight({
	commit
}, weight) {

	try {
		let weightInKg = 0;
		
		// 将输入转换为小写以便统一比较
		const weightLower = weight.toLowerCase();

		// 使用正则表达式提取数字部分（包括符号和小数点）
		const weightMatch = weight.match(/[+-]?\d*\.?\d+/);

		if (weightMatch) {
			const weightValue = parseFloat(weightMatch[0]);

			if (!isNaN(weightValue)) {
				// 根据单位转换（使用小写比较）
				if (weightLower.includes('g') && !weightLower.includes('kg')) {
					weightInKg = weightValue / 1000; // 克转千克
					console.log(`克转千克: ${weightValue}g -> ${weightInKg}kg`);
				} else if (weightLower.includes('t') || weightLower.includes('吨')) {
					weightInKg = weightValue * 1000; // 吨转千克
					console.log(`吨转千克: ${weightValue}t -> ${weightInKg}kg`);
				} else if (weightLower.includes('lb') || weightLower.includes('磅')) {
					weightInKg = weightValue * 0.453592; // 磅转千克
					console.log(`磅转千克: ${weightValue}lb -> ${weightInKg}kg`);
				} else {
					weightInKg = weightValue; // 已经是千克或其他默认单位
					console.log(`直接使用: ${weightValue} -> ${weightInKg}kg`);
				}

				commit('SET_WEIGHT', weightInKg);
				console.log(`最终重量: ${weightInKg}kg`);
			} else {
				console.warn('⚠️ 解析出的数字无效:', weightMatch[0]);
			}
		} else {
			console.warn('⚠️ 未找到有效的数字:', weight);
		}

	} catch (error) {
		console.error('处理重量数据时出错:', error, weight);
	}
},
// 更新重量
updateWeightStr({
	commit
}, weight) {

	try {
		let weightInG = 0;
		
		// 将输入转换为小写以便统一比较
		const weightLower = weight.toLowerCase();

		// 使用正则表达式提取数字部分（包括符号和小数点）
		const weightMatch = weight.match(/[+-]?\d*\.?\d+/);

		if (weightMatch) {
			const weightValue = parseFloat(weightMatch[0]);

			if (!isNaN(weightValue)) {
				// 根据单位转换到克（使用小写比较）
				if (weightLower.includes('kg') || weightLower.includes('千克')) {
					weightInG = weightValue * 1000; // 千克转克
					console.log(`千克转克: ${weightValue}kg -> ${weightInG}g`);
				} else if (weightLower.includes('t') || weightLower.includes('吨')) {
					weightInG = weightValue * 1000000; // 吨转克
					console.log(`吨转克: ${weightValue}t -> ${weightInG}g`);
				} else if (weightLower.includes('lb') || weightLower.includes('磅')) {
					weightInG = weightValue * 453.592; // 磅转克
					console.log(`磅转克: ${weightValue}lb -> ${weightInG}g`);
				} else {
					weightInG = weightValue; // 默认已经是克
					console.log(`直接使用: ${weightValue} -> ${weightInG}g`);
				}

				commit('SET_WEIGHT_STR', weightInG);
				console.log(`最终重量: ${weightInG}g`);
			} else {
				console.warn('⚠️ 解析出的数字无效:', weightMatch[0]);
			}
		} else {
			console.warn('⚠️ 未找到有效的数字:', weight);
		}

	} catch (error) {
		console.error('处理重量数据时出错:', error, weight);
	}
},

		// 更新电池电量
		updateBattery({
			commit
		}, batteryLevel) {
			const parsedLevel = parseInt(batteryLevel);
			if (!isNaN(parsedLevel)) {
				commit('SET_BATTERY_LEVEL', parsedLevel);
			} else {
				console.warn('⚠️ 无效的电池电量:', batteryLevel);
			}
		},

		// 批量更新设备状态
		updateDeviceState({
			commit
		}, deviceState) {
			if (deviceState && typeof deviceState === 'object') {
				commit('UPDATE_DEVICE_STATE', deviceState);
			} else {
				console.warn('⚠️ 无效的设备状态对象:', deviceState);
			}
		},

		// 连接设备
		connectDevice({
			commit,
			dispatch
		}) {
			commit('SET_STATUS', 'connecting');

			// 模拟连接过程
			setTimeout(() => {
				commit('SET_STATUS', 'connected');
				dispatch('getDeviceInfo');
			}, 2000);
		},

		// 断开连接
		disconnectDevice({
			commit
		}) {
			commit('SET_STATUS', 'disconnected');
			commit('SET_WEIGHT', 0);
		},

		// 获取设备信息
		getDeviceInfo({
			commit
		}) {
			// 模拟获取设备信息
			const deviceInfo = {
				deviceName: '智能电子秤',
				batteryLevel: 85
			};
			commit('UPDATE_DEVICE_STATE', deviceInfo);
		},

		// 重置设备状态
		resetDevice({
			commit
		}) {
			commit('UPDATE_DEVICE_STATE', {
				deviceName: '电子秤',
				status: 'disconnected',
				weight: 0,
				batteryLevel: -1
			});
		}
	}
};

export default weightStore;